package com.ycb.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycb.entity.Goods;
import com.ycb.mapper.GoodsMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 黄泽群
 * @since 2023-12-11
 */
@Slf4j
@Service
@LocalTCC
@RequiredArgsConstructor
public class GoodsService extends ServiceImpl<GoodsMapper, Goods> {

    @Transactional // 单数据源内部可以通过Transactional保证单节点事务
    @TwoPhaseBusinessAction(name = "subStock",commitMethod = "subStockCommit",rollbackMethod = "subStockRollback",isDelayReport = true,useTCCFence = true)
    public Goods subStock(BusinessActionContext context,
                          @BusinessActionContextParameter("id") Integer id,
                          @BusinessActionContextParameter("num")  Integer num) {
        log.warn(" GoodsService.subStock xid :{} branchId:{} getActionContext:{}",context.getXid(),context.getBranchId()
                ,context.getActionContext());
        Goods goods = super.getById(id);
        goods.setStock(goods.getStock() - num);
        super.updateById(goods);
        return goods;
    }

    public void subStockCommit(BusinessActionContext context){
        log.warn(" subStockCommit xid :{} branchId:{} id:{} num:{}",context.getXid(),context.getBranchId()
                ,context.getActionContext("id"),context.getActionContext("num"));
        String xid = context.getXid();
    }

    public void subStockRollback(BusinessActionContext context){
        log.warn(" subStockRollback xid :{} branchId:{} id:{} num:{}",context.getXid(),context.getBranchId()
                ,context.getActionContext("id"),context.getActionContext("num"));
        String xid = context.getXid();
        Integer id = context.getActionContext("id", Integer.class);
        Integer num = context.getActionContext("num", Integer.class);
        Goods goods = super.getById(id);
        goods.setStock(goods.getStock() + num);
        super.updateById(goods);
    }

}
